<template>
  <div class="shop-rent-management">

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-card shadow="never">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="店铺">
            <el-select 
              v-model="searchForm.shopId" 
              placeholder="请选择店铺" 
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="shop in shopList"
                :key="shop.id"
                :label="shop.shopName"
                :value="shop.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="支付状态">
            <el-select 
              v-model="searchForm.paymentStatus" 
              placeholder="请选择支付状态" 
              clearable
              style="width: 120px"
            >
              <el-option label="未支付" :value="0" />
              <el-option label="已支付" :value="1" />
              <el-option label="逾期" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="租金期间">
            <el-input
              v-model="searchForm.rentPeriod"
              placeholder="请输入租金期间"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="租金月份">
            <el-input
              v-model="searchForm.rentMonth"
              placeholder="请输入租金月份"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="租金日期">
            <el-date-picker
              v-model="searchForm.rentDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-card shadow="never">
        <div class="operation-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增租金记录
          </el-button>
          <el-button type="success" @click="handleBatchPayment" :disabled="selectedRows.length === 0">
            <el-icon><Money /></el-icon>
            批量支付
          </el-button>
          <el-button type="warning" @click="handleBatchRemind" :disabled="selectedRows.length === 0">
            <el-icon><Bell /></el-icon>
            批量催缴
          </el-button>
          <el-button type="info" @click="handleExport" :disabled="rentList.length === 0">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="info" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-area">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-value">{{ formatMoney(stats.totalAmount) }}</div>
              <div class="stats-label">总租金金额(元)</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-value paid">{{ formatMoney(stats.paidAmount) }}</div>
              <div class="stats-label">已支付金额(元)</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-value unpaid">{{ formatMoney(stats.unpaidAmount) }}</div>
              <div class="stats-label">未支付金额(元)</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-value overdue">{{ formatMoney(stats.overdueAmount) }}</div>
              <div class="stats-label">逾期金额(元)</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-card shadow="never">
        <el-table 
          :data="rentList" 
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="shopName" label="店铺名称" min-width="120" />
          <el-table-column prop="rentMonth" label="租金月份" width="100" />
          <el-table-column prop="rentAmount" label="租金金额" width="120">
            <template #default="{ row }">
              <span class="money-text">¥{{ formatMoney(row.rentAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="isMonthlyRent" label="月度租金" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isMonthlyRent === 1 ? 'success' : 'info'" size="small">
                {{ row.isMonthlyRent === 1 ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="leaseStartDate" label="租赁开始" width="100" />
          <el-table-column prop="leaseEndDate" label="租赁结束" width="100" />
          <el-table-column prop="paymentDate" label="支付日期" width="120">
            <template #default="{ row }">
              {{ row.paymentDate || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="paymentStatusName" label="支付状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                {{ row.paymentStatusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="paymentMethod" label="支付方式" width="120">
            <template #default="{ row }">
              {{ row.paymentMethod || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="receiptNumber" label="收据号" min-width="120">
            <template #default="{ row }">
              {{ row.receiptNumber || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleView(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button 
                v-if="row.paymentStatus === 0" 
                type="success" 
                size="small" 
                @click="handlePayment(row)"
              >
                <el-icon><Money /></el-icon>
                支付
              </el-button>
              <el-button 
                v-if="row.paymentStatus === 0" 
                type="warning" 
                size="small" 
                @click="handleRemind(row)"
              >
                <el-icon><Bell /></el-icon>
                催缴
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-card shadow="never">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>

    <!-- 租金详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="租金详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <ShopRentDetail v-if="detailDialogVisible" :rent-id="selectedRentId" />
    </el-dialog>

    <!-- 租金表单对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="formTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <ShopRentForm 
        v-if="formDialogVisible" 
        :rent-id="selectedRentId"
        :mode="formMode"
        @success="handleFormSuccess"
        @cancel="handleFormCancel"
      />
    </el-dialog>

    <!-- 支付对话框 -->
    <el-dialog
      v-model="paymentDialogVisible"
      title="租金支付"
      width="500px"
      :close-on-click-modal="false"
    >
      <ShopRentPayment 
        v-if="paymentDialogVisible" 
        :rent-id="selectedRentId"
        @success="handlePaymentSuccess"
        @cancel="handlePaymentCancel"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  View, 
  Edit, 
  Delete,
  Money,
  Bell
} from '@element-plus/icons-vue'
import ShopRentDetail from './components/ShopRentDetail.vue'
import ShopRentForm from './components/ShopRentForm.vue'
import ShopRentPayment from './components/ShopRentPayment.vue'
import { shopRentApi } from '@/api/shop-rent'
import { shopApi } from '@/api/shop'
import { shopOwnerApi } from '@/api/shop-owner'
import type { ShopRentRecordVO, ShopVO, ShopOwnerVO } from './types'
import type { ShopRentQueryParams, ShopRentFormData, PaymentInfo, ShopRentStatistics } from '@/api/shop-rent'

// 响应式数据
const loading = ref(false)
const rentList = ref<ShopRentRecordVO[]>([])
const shopList = ref<ShopVO[]>([])
const selectedRows = ref<ShopRentRecordVO[]>([])

// 搜索表单
const searchForm = reactive({
  shopId: undefined as number | undefined,
  paymentStatus: undefined as number | undefined,
  rentPeriod: '',
  rentMonth: '',
  rentDateRange: null as [string, string] | null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框状态
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const paymentDialogVisible = ref(false)
const selectedRentId = ref<number | null>(null)
const formMode = ref<'add' | 'edit'>('add')

// 统计数据
const stats = reactive({
  totalAmount: 0,
  paidAmount: 0,
  unpaidAmount: 0,
  overdueAmount: 0
})

// 计算属性
const formTitle = computed(() => {
  return formMode.value === 'add' ? '新增租金记录' : '编辑租金记录'
})

// 生命周期
onMounted(() => {
  loadRentList()
  loadShopList()
})

// 方法
const loadRentList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const queryParams: ShopRentQueryParams = {
      current: pagination.current,
      size: pagination.size,
      shopId: searchForm.shopId,
      paymentStatus: searchForm.paymentStatus,
      rentPeriod: searchForm.rentPeriod || undefined,
      rentMonth: searchForm.rentMonth || undefined,
      startDate: searchForm.rentDateRange?.[0],
      endDate: searchForm.rentDateRange?.[1]
    }
    
    // 调用API接口
    const response = await shopRentApi.getRentRecordPage(queryParams)
    
    if (response.code === 200) {
      rentList.value = response.data.records
      pagination.total = response.data.total
      pagination.current = response.data.current
      pagination.size = response.data.size
      
      // 计算统计数据
      calculateStats(rentList.value)
    } else {
      ElMessage.error(response.message || '加载租金列表失败')
    }
  } catch (error) {
    ElMessage.error('加载租金列表失败')
    console.error('加载租金列表失败:', error)
  } finally {
    loading.value = false
  }
}

const loadShopList = async () => {
  try {
    const response = await shopApi.getShopPage({
      current: 1,
      size: 100 // 获取店铺用于下拉选择，限制在100以内
    })
    
    if (response.code === 200) {
      shopList.value = response.data.records
    } else {
      ElMessage.error(response.message || '加载店铺列表失败')
    }
  } catch (error) {
    ElMessage.error('加载店铺列表失败')
    console.error('加载店铺列表失败:', error)
  }
}


const filterRentList = (data: ShopRentRecordVO[]) => {
  return data.filter(rent => {
    if (searchForm.shopId !== undefined && rent.shopId !== searchForm.shopId) return false
    if (searchForm.paymentStatus !== undefined && rent.paymentStatus !== searchForm.paymentStatus) return false
    if (searchForm.rentPeriod && rent.rentPeriod !== searchForm.rentPeriod) return false
    if (searchForm.rentMonth && rent.rentMonth !== searchForm.rentMonth) return false
    if (searchForm.rentDateRange && searchForm.rentDateRange.length === 2) {
      const [startDate, endDate] = searchForm.rentDateRange
      if (rent.rentStartDate < startDate || rent.rentEndDate > endDate) return false
    }
    return true
  })
}

const calculateStats = (data: ShopRentRecordVO[]) => {
  // 确保统计数据安全计算，遵循《Element Plus组件编码规范权威标准声明.md》规范
  stats.totalAmount = data.reduce((sum, rent) => {
    const amount = typeof rent.rentAmount === 'number' ? rent.rentAmount : 0
    return sum + amount
  }, 0)
  
  stats.paidAmount = data
    .filter(rent => rent.paymentStatus === 1)
    .reduce((sum, rent) => {
      const amount = typeof rent.rentAmount === 'number' ? rent.rentAmount : 0
      return sum + amount
    }, 0)
  
  stats.unpaidAmount = data
    .filter(rent => rent.paymentStatus === 0)
    .reduce((sum, rent) => {
      const amount = typeof rent.rentAmount === 'number' ? rent.rentAmount : 0
      return sum + amount
    }, 0)
  
  stats.overdueAmount = data
    .filter(rent => rent.paymentStatus === 2)
    .reduce((sum, rent) => {
      const amount = typeof rent.rentAmount === 'number' ? rent.rentAmount : 0
      return sum + amount
    }, 0)
}

const handleSearch = () => {
  pagination.current = 1
  loadRentList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    shopId: undefined,
    paymentStatus: undefined,
    rentPeriod: '',
    rentMonth: '',
    rentDateRange: null
  })
  handleSearch()
}

const handleAdd = () => {
  selectedRentId.value = null
  formMode.value = 'add'
  formDialogVisible.value = true
}

const handleEdit = (row: ShopRentRecordVO) => {
  selectedRentId.value = row.id
  formMode.value = 'edit'
  formDialogVisible.value = true
}

const handleView = (row: ShopRentRecordVO) => {
  selectedRentId.value = row.id
  detailDialogVisible.value = true
}

const handlePayment = (row: ShopRentRecordVO) => {
  selectedRentId.value = row.id
  paymentDialogVisible.value = true
}

const handleRemind = async (row: ShopRentRecordVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要催缴店铺"${row.shopName}"的租金吗？`, 
      '催缴确认', 
      {
        type: 'warning',
        confirmButtonText: '确定催缴',
        cancelButtonText: '取消'
      }
    )
    
    // 模拟催缴操作
    ElMessage.success('催缴通知已发送')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('催缴失败')
    }
  }
}

const handleDelete = async (row: ShopRentRecordVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除店铺"${row.shopName}"的租金记录吗？删除后不可恢复！`, 
      '删除确认', 
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    // 调用删除API
    loading.value = true
    const response = await shopRentApi.deleteRentRecord(row.id)
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      loadRentList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  } finally {
    loading.value = false
  }
}

const handleBatchPayment = () => {
  ElMessage.info('批量支付功能开发中...')
}

const handleBatchRemind = () => {
  ElMessage.info('批量催缴功能开发中...')
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleRefresh = () => {
  loadRentList()
}

const handleSelectionChange = (selection: ShopRentRecordVO[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadRentList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadRentList()
}

const handleFormSuccess = () => {
  formDialogVisible.value = false
  loadRentList()
  ElMessage.success(formMode.value === 'add' ? '新增成功' : '编辑成功')
}

const handleFormCancel = () => {
  formDialogVisible.value = false
}

const handlePaymentSuccess = () => {
  paymentDialogVisible.value = false
  loadRentList()
  ElMessage.success('支付成功')
}

const handlePaymentCancel = () => {
  paymentDialogVisible.value = false
}

// 工具方法
const getPaymentStatusTagType = (status: number) => {
  const typeMap = {
    0: 'danger',  // 未支付
    1: 'success', // 已支付
    2: 'warning'  // 逾期
  }
  return typeMap[status as keyof typeof typeMap] || 'info'
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 安全的金额格式化函数，遵循《Element Plus组件编码规范权威标准声明.md》规范
const formatMoney = (amount: any): string => {
  try {
    if (amount === null || amount === undefined || amount === '') {
      return '0.00'
    }
    
    // 确保是数字类型
    const num = typeof amount === 'number' ? amount : parseFloat(amount)
    
    // 检查是否为有效数字
    if (isNaN(num) || !isFinite(num)) {
      return '0.00'
    }
    
    // 格式化数字，保留两位小数
    return num.toFixed(2)
  } catch (error) {
    console.warn('formatMoney error:', error, 'amount:', amount)
    return '0.00'
  }
}
</script>

<style scoped>
.shop-rent-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.operation-area {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.stats-area {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-content {
  padding: 20px;
}

.stats-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.stats-value.paid {
  color: #67c23a;
}

.stats-value.unpaid {
  color: #f56c6c;
}

.stats-value.overdue {
  color: #e6a23c;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
}

.money-text {
  color: #f56c6c;
  font-weight: 600;
}

:deep(.el-card__body) {
  padding: 16px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
